﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using System.Collections.Generic;
using System.Net.Mail;
using System.Net;
using KenLib.BusinessObject;

public partial class JOINT_frmJ_InterviewTraineeListSendEmail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ((JOINT_MstPage_JOINT)this.Master).changeTitle("面接候補者メール送信");
        ((JOINT_MstPage_JOINT)this.Master).HideLiArea("frmJ_InterviewTraineeListSendEmail");

        if (Session["人コード"] == null)
        {
            Response.Redirect("../frmD_Login.aspx");
        }
        else if (Session["人コード"].ToString() == "")
        {
            Response.Redirect("../frmD_Login.aspx");
        }

        if (!IsPostBack){
            bind面接日();
            SetTime();
            SetMinute();
            if (Session["役"] != null && Session["役"].ToString() == "3") {
                btn_担当確認.Text = "担当確認";
            }
            else if (Session["役"] != null && Session["役"].ToString() == "2") {
                btn_担当確認.Text = "確認";
            }

            string ER00001 = GetError("ER00001");
            string ER00005 = GetError("ER00005");
            string ER00006 = GetError("ER00006");
            string ER00007 = GetError("ER00007");

            RequiredFieldValidator_ddl面接日.ErrorMessage = ER00007;
            RequiredFieldValidator内容.ErrorMessage = ER00001;
            RequiredFieldValidator面接日.ErrorMessage = ER00001;
            CustomValidator面接日.ErrorMessage = ER00005;
            CustomValidator面接日1.ErrorMessage = ER00006;
            RequiredFieldValidator来社時間時.ErrorMessage = ER00007;
            RequiredFieldValidator来社時間分.ErrorMessage = ER00007;
            RequiredFieldValidator場所.ErrorMessage = ER00001;
            RequiredFieldValidator持参物.ErrorMessage = ER00001;
            RequiredFieldValidator問い合わせ先.ErrorMessage = ER00001;
        }
    }
    /// <summary>
    /// OnSelectedIndexChanged: lay gia tri o dropdownList ddl_面接日 sau do select hien thi len form.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LoadInfo面接情報(object sender, EventArgs e)
    {
        int 担当確認 = 0;
        int value_id = Int32.Parse(ddl_面接日.SelectedValue);
        面接情報Manager frm = new 面接情報Manager();
        DataTable dt = frm.LoadInfo面接情報(value_id);
        if (dt.Rows.Count > 0)
        {
            try
            {
                txt_内容.Text = dt.Rows[0]["内容2"].ToString();
                txt_面接日.Text = dt.Rows[0]["来社日2"].ToString() != "" ? DateTime.Parse(dt.Rows[0]["来社日2"].ToString()).ToString("yyyy/MM/dd") : "";
                string 来社時期2 = dt.Rows[0]["来社時期2"].ToString();
                if (来社時期2.Length > 0)
                {
                    ddl_来社時間時.SelectedValue = 来社時期2.Substring(0, 2);
                    ddl_来社時間分.SelectedValue = 来社時期2.Substring(2, 2);
                }
                else
                {
                    ddl_来社時間時.SelectedValue = "-1";
                    ddl_来社時間分.SelectedValue = "-1";
                }
                txt_場所.Text = dt.Rows[0]["場所2"].ToString();
                txt_持参物.Text = dt.Rows[0]["持参物2"].ToString();
                txt_問い合わせ先.Text = dt.Rows[0]["問い合わせ先2"].ToString();

                担当確認 = Int32.Parse(dt.Rows[0]["担当確認"].ToString());
                SetValueForControl(0);
            }
            catch (Exception ex)
            {
                Response.Write(ex.StackTrace);
                return;
            }

            if (Session["役"] != null && Session["役"].ToString() == "3")
            {
                switch (担当確認)
                {
                    case 0:
                        btn_担当確認.Enabled = true;
                        btn_メール送信.Enabled = false;
                        break;
                    case 1:
                        btn_担当確認.Enabled = false;
                        btn_メール送信.Enabled = false;
                        break;
                    case 2:
                        btn_担当確認.Enabled = false;
                        btn_メール送信.Enabled = true;
                        break;
                }
            }
            else if (Session["役"] != null && Session["役"].ToString() == "2")
            {
                switch (担当確認)
                {
                    case 0:
                        btn_担当確認.Enabled = false;
                        btn_メール送信.Enabled = true;
                        break;
                    case 1:
                        btn_担当確認.Enabled = true;
                        btn_メール送信.Enabled = true;
                        break;
                    case 2:
                        btn_担当確認.Enabled = false;
                        btn_メール送信.Enabled = true;
                        break;
                }
            }
        }
        else {
            txt_内容.Text = "";
            txt_面接日.Text = "";
            ddl_来社時間時.SelectedValue = "-1";
            ddl_来社時間分.SelectedValue = "-1";
            txt_場所.Text = "";
            txt_持参物.Text = "";
            txt_問い合わせ先.Text = "";
        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }

    /// <summary>
    /// Load du lieu vao dropdownList ddl_面接日
    /// </summary>
    protected void bind面接日() 
    {
        try
        {        
            面接情報Manager frm = new 面接情報Manager();
            DataTable dt = frm.Select面接日();
            if (dt.Rows.Count > 0)
            {
                ddl_面接日.DataSource = dt;
                ddl_面接日.DataTextField = "面接日";
                ddl_面接日.DataValueField = "ID";
                ddl_面接日.DataBind();

                ListItem 選択 = new ListItem("[選択]", "-1");
                ddl_面接日.Items.Insert(0, 選択);
            }
        }
        catch(Exception ex){
            Response.Write(ex.StackTrace);
        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }
    public void SetTime()
    {
        for (int i = 8; i <= 17; i++)
        {
            if (i < 10)
            {
                ddl_来社時間時.Items.Add("0" + i.ToString());

            }
            else
            {
                ddl_来社時間時.Items.Add(i.ToString());
            }

        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }
    public void SetMinute()
    {
        //for (int i = 0; i <= 60; i++)
        //{
        //    if (i < 10)
        //    {
        //        ddl_来社時間分.Items.Add("0" + i.ToString());
        //    }
        //    else
        //    {
        //        ddl_来社時間分.Items.Add(i.ToString());
        //    }

        //}
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
    }

    /// <summary>
    /// Ham send mail
    /// </summary>
    /// <param name="to"></param>
    /// <param name="subject"></param>
    /// <param name="obj"></param>
    public void SendMailMessage(string to, string subject, 面接情報 obj)
    {
        try
        {
            string body = "";
            body += "<body>";
            body += obj.内容2;
            body += "<br/><br/>";
            body += "Thời gian: ";
            body += obj.来社日2.ToString().Substring(0, 10);
            body += "            ";
            body += " Vào lúc ";
            body += obj.来社時期2.Substring(0, 2);
            body += ":";
            body += obj.来社時期2.Substring(2, 2);
            body += "<br/>";
            body += "Địa điểm: ";
            body += obj.場所2;
            body += "<br/>";
            body += "Các tài liệu cần mang theo: ";
            body += obj.持参物2;
            body += "<br/>";
            body += "Địa chỉ nơi hồi đáp: ";
            body += obj.問い合わせ先2;
            body += "</body>";

            MailMessage mMailMessage = new MailMessage();
            mMailMessage.From = new MailAddress("contact@xanhbiec.com", "Xanh Biec");
            mMailMessage.To.Add(new MailAddress(to));

            mMailMessage.Subject = "Xin chào " +  subject;
            mMailMessage.Body = body;
            
            mMailMessage.IsBodyHtml = true;
            mMailMessage.Priority = MailPriority.Normal;

            SmtpClient mSmtpClient = new SmtpClient();
            mSmtpClient.Host = "smtp.xanhbiec.com";
            mSmtpClient.Credentials = new NetworkCredential("contact@xanhbiec.com", "xanhbiec");

            mSmtpClient.Send(mMailMessage);
            mMailMessage.To.Clear();
        }
        catch { }
    }
    protected void btn_担当確認_Click(object sender, EventArgs e)
    {
        if (Session["役"] != null)
        {
            int value_id = Int32.Parse(ddl_面接日.SelectedValue);

            面接情報Manager frm = new 面接情報Manager();
            面接情報 obj = new 面接情報();
            obj.ID = value_id;
            obj.来社日2 = DateTime.Parse(txt_面接日.Text);
            string 来社時間時 = ddl_来社時間時.SelectedValue;
            string 来社時間分 = ddl_来社時間分.SelectedValue;
            obj.来社時期2 = 来社時間時 + 来社時間分;
            obj.場所2 = txt_場所.Text;
            obj.持参物2 = txt_持参物.Text;
            obj.問い合わせ先2 = txt_問い合わせ先.Text;
            obj.内容2 = txt_内容.Text;

            int 役 = Int32.Parse(Session["役"].ToString());
            int button_type = 0;
            frm.UpdateInfo面接情報(obj, 役, button_type);

            Response.Redirect("frmJ_TraineeManager.aspx");
        }
    }
    protected void btn_メール送信_Click(object sender, EventArgs e)
    {
        SetValueForControl(1);

        if (Session["役"] != null)
        {
            int value_id = Int32.Parse(ddl_面接日.SelectedValue);

            面接情報Manager frm = new 面接情報Manager();
            面接情報 obj = new 面接情報();
            obj.ID = value_id;
            obj.来社日2 = DateTime.Parse(txt_面接日.Text);
            string 来社時間時 = ddl_来社時間時.SelectedValue;
            string 来社時間分 = ddl_来社時間分.SelectedValue;
            obj.来社時期2 = 来社時間時 + 来社時間分;
            obj.場所2 = txt_場所.Text;
            obj.持参物2 = txt_持参物.Text;
            obj.問い合わせ先2 = txt_問い合わせ先.Text;
            obj.内容2 = txt_内容.Text;

            int 役 = Int32.Parse(Session["役"].ToString());
            int button_type = 1;
            
            string 氏名 = "";
            string Email = "";
            
            DataTable dt = frm.SelectMail面接情報(value_id);
            if (dt.Rows.Count > 0) {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Email = dt.Rows[i]["Email"].ToString();
                    氏名 = dt.Rows[i]["氏名"].ToString();
                    SendMailMessage(Email, 氏名, obj);
                }

                int result = frm.UpdateInfo面接情報(obj, 役, button_type);
                
                Response.Redirect("frmJ_TraineeManager.aspx");
            } else {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('"+ GetError("ER00008") +"');", true);
				ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "regis", "startup();", true);
            }
        }
    }

    /// <summary>
    /// ham chuyen doi ki tu < >
    /// </summary>
    /// <param name="root"></param>
    /// <returns></returns>
    public static Control[] FlattenHierachy(Control root)
    {
        List<Control> list = new List<Control>();
        list.Add(root);
        if (root.HasControls())
        {
            foreach (Control control in root.Controls)
            {
                list.AddRange(FlattenHierachy(control));
            }
        }
        return list.ToArray();
    }
    protected void SetValueForControl(int type)
    {
        Control[] allControls = FlattenHierachy(Page);
        foreach (Control control in allControls)
        {
            TextBox textBox = control as TextBox;
            if (textBox != null)
            {
                if (type == 1)
                {
                    textBox.Text = textBox.Text.Replace("<", "&lt;");
                    textBox.Text = textBox.Text.Replace(">", "&gt;");
                }
                else
                {
                    textBox.Text = textBox.Text.Replace("&lt;", "<");
                    textBox.Text = textBox.Text.Replace("&gt;", ">");
                }
            }
        }
    }

    /// <summary>
    /// ham lay loi tu database
    /// </summary>
    /// <param name="errorid"></param>
    /// <returns></returns>
    public String GetError(string errorid)
    {
        string error = "";
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        if (dt.Rows.Count > 0)
            error = dt.Rows[0][2].ToString();
        return error;
    }
}
